<?

  error_reporting(E_ALL);
  ini_set('display_errors', 1);

include_once 'controller.inc.php';

$user_email = $_COOKIE['user'];
$action = $_POST['action'];

  print_r($_POST);

if ($action == 'Join Event') {
  $role_id = $_POST['join_role'];

  $db_link = db_connect();
  $user = db_getUserByEmail($user_email);
  $role = db_getRole($role_id);
  
  if (is_null($role->getUser())) {
    $role->setUser($user->getID());
    db_updateRole($role);
    $redirect_to = 'view_event.php?id='.$role->getEventID().'&success=Event_joined';
  }
  else {
    $redirect_to = 'dashboard.php?failure=auth';
  }
  
  db_disconnect($db_link);
}
else if ($action == 'Cancel') {
  $role_id = $_POST['unjoin_role'];

  $db_link = db_connect();
  $user = db_getUserByEmail($user_email);
  $role = db_getRole($role_id);
  
  if ($role->getUserID() == $user->getID()) {
    $role->setUser(0);
    db_updateRole($role);
    $redirect_to = 'view_event.php?id='.$role->getEventID().'&success=Left_event';
  }
  else {
    $redirect_to = 'dashboard.php?failure=auth';
  }
  
  db_disconnect($db_link);
}

header('Location: '.$redirect_to);

?>
